#ifndef _DEFER_H_
#define _DEFER_H_

#include <vector>
#include <functional>

class defer
{
public:
    using defer_function = std::function<void()>;

private:
    std::vector<defer_function> defer_list_;

public:
    explicit defer() {};
    explicit defer(defer_function && handle) {
        defer_list_.push_back(std::forward<defer_function>(handle));
    };
    ~defer() {
        try{
            for (auto iter = defer_list_.rbegin(); iter != defer_list_.rend(); iter++) {
                (*iter)();
            }
        } catch(...) {
        }
    };
    void add_defer(defer_function handle) {
        defer_list_.push_back(std::move(handle));
    }
};

#define DEFER(func_code)                defer __defer_object__##__LINE__([&] () {func_code;});
#define MORE_DEFER(obj, func_code)      (obj).add_defer( [&] () {func_code;});

#endif
